<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Controllers;

use Sun\Sun;
use Sun\Html;
use Sun\Utils;
use Sun\Validators;
use App\Models;

class Admin extends \Sun\Controller {
    public function __construct() {
        parent::__construct("Main");

    }

    public function Action($req, $name = null) {
        $session = new Models\Session();
        $usr = $session->UserType();
        if ($session->UserType() == "ADMIN") {
            parent::Action($req, $name);
        } else {
            Sun::view("Index\\NotFound")->Render(null);
        }
    }

    public function MainAction($req) {
        if (isset($req->data['p'])){
            $v = $req->data['p'];
            $this->RenderView($v, $req->data);
        } else if (isset($req->data['m'])) {
            $v = $req->data['m'];
            $this->RenderViewScene($v, $req->data);
        } else {
            $this->RenderView("Admin\\Main", $req->data);
        }
    }

    public function AddUserAction($req) {
        if ($req->method == "GET")
            return header("Location: ?u=Lib");

        Utils::TrimArray($req->data);

        $kit = new Validators\ValidatorKit(array(
            'date' => new Validators\ArrayValidator(
                new Validators\ValidatorSet(array(
                    new Validators\DateValidator(), new Validators\NullValidator()))),

            'name' => new Validators\ArrayValidator(
                new Validators\ValidatorSet(array(
                    new Validators\NameValidator(), new Validators\NullValidator()))),

            'pass' => new Validators\NullValidator()
        ));

        $res = new \Sun\Response();
        try {
            if (!$kit->Verify(array(
                    'name' => Utils::ValuesAt($req->data, array('fullname', 'login')),
                    'date' => Utils::ValuesAt($req->data, array('reg_date', 'reg_comp')),
                    'pass' => $req->data['pass']))) {
                throw new \Sun\Exception('', 1);
            }

            if (strtotime($req->data['reg_date']) >= strtotime($req->data['reg_comp']))
                throw new \Sun\Exception ('', 2);

            $user = new Models\User();
            $user->AddUser($req->data);
            $res->STAT = 'OK';

        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $kit->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('log' => 'Дата окончания больше даты регистрации');
                    break;
                default:
                    $res->ERR = array('log' => 'Не удалось создать пользователя');
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function AltUserAction($req) {
        if ($req->method == "GET")
            return header("Location: ?p=Enter");
        Utils::TrimArray($req->data);

        $kit = new Validators\ValidatorKit(array(
            'date' => new Validators\ArrayValidator(
                new Validators\ValidatorSet(array(
                    new Validators\DateValidator(), new Validators\NullValidator()))),

            'name' => new Validators\ArrayValidator(
                new Validators\ValidatorSet(array(
                    new Validators\NameValidator(), new Validators\NullValidator()))),

            'pass' => new Validators\NullValidator()
        ));

        $res = new \Sun\Response();
        try {
            if (!$kit->Verify(array(
                    'name' => Utils::ValuesAt($req->data, array('fullname', 'login')),
                    'date' => Utils::ValuesAt($req->data, array('reg_date', 'reg_comp')),
                    'pass' => $req->data['pass']))) {
                throw new \Sun\Exception('', 1);
            }

            if (strtotime($req->data['reg_date']) >= strtotime($req->data['reg_comp']))
                throw new \Sun\Exception ('', 2);

            $user = new Models\User();
            $user->AltUser($req->data);
            $res->STAT = 'OK';

        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $kit->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('log' => 'Дата окончания больше даты регистрации');
                    break;
                default:
                    $res->ERR = array('log' => 'Не удалось создать пользователя');
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function DelUserAction($req) {
        $res = new \Sun\Response();
        try {
            $user = new Models\User();
            $user->DelUser($req->data['user_id']);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                default:
                    $res->ERR = array('log' => 'Не возможно удалить действующего пользователя');
                    break;
            }
        }
        echo $res->ToJSON();
    }

}


